package com.dg.gaming.tictactoe.client;

import com.dg.gaming.client.gui.DGGameTable;
import com.dg.gaming.tictactoe.common.TicTacToeModel;
import com.dg.gaming.tictactoe.common.MsgTicTacToeMove;
import nanoxml.XMLElement;
import com.dg.gaming.api.common.GameModel;
import com.dg.gaming.api.common.AbstractConnectionThread;
import info.clearthought.layout.TableLayout;
import com.dg.gaming.client.gui.DGPanel;
import com.dg.gaming.client.gui.PlayerComponent;
import com.dg.gaming.client.*;

public class TicTacToeGameTableFrame extends DGGameTable {
    private static final int WIDTH = 510, HEIGHT = 435;
    private TicTacToeModel model=new TicTacToeModel();
    private TicTacToeBoardComponent boardComponent;
    private TicTacToeController controller;


    public TicTacToeGameTableFrame() {
        super(WIDTH, HEIGHT);

    }
    public void connectOK(AbstractConnectionThread c) {
        super.connectOK(c);
        TableConnection conn=(TableConnection)c;
        boardComponent = new TicTacToeBoardComponent(model); // board
        model.addObserver(boardComponent); // board observes model

        // Create controller which updates model and controlls the view
        controller = new TicTacToeController(model, boardComponent);
        controller.setConnection(conn.getTableConn()); // connection
        boardComponent.setController(controller);

        // Add view to a panel and set on table frame
        double[][] sizes = { {10, TableLayout.PREFERRED, 10, TableLayout.FILL,
                           10}, {10, TableLayout.PREFERRED, TableLayout.FILL}
        };
        DGPanel panel = new DGPanel(sizes); // create a panel
        panel.add(boardComponent, "1,1,l,t"); // add board to panel
        panel.add(new PlayerComponent(conn.getTableConn(), 0), "3,1,l,t"); // add board to panel
        panel.add(new PlayerComponent(conn.getTableConn(), 1), "3,1,l,b"); // add board to panel
        setGamePanel(panel); // add panel to table frame

        // Set up MVC classes in super class
        setupMVC(model, boardComponent, controller);

    }
    @Override
    public void receiveMessage(XMLElement message) {

        String messageType = message.getName();

        if (messageType.equals(MsgTicTacToeMove.XML_NAME)) {
            MsgTicTacToeMove move = new MsgTicTacToeMove(message);
            model.setData(move.getX(), move.getY(), move.getValue());
        }
    }

    public GameModel getGameModel() {
        return model;
    }
    public static void main(String[] args) {
        new TicTacToeGameTableFrame();
    }

}
